package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import com.heima.common.util.AppThreadLocalUtil;
import com.heima.user.dto.ApAuthor;
import com.heima.user.dto.FollowBehaviorDto;
import com.heima.user.dto.LoginDto;
import com.heima.user.dto.UserRelationDto;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserFollow;
import com.heima.user.feign.ArticleFeign;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.IApUserFollowService;
import com.heima.user.service.IApUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-03-12
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements IApUserService {

    @Override
    public ResponseResult loginAuth(LoginDto dto) {
        //判断是否有手机号,密码,设备id
        if (dto==null||(StringUtils.isEmpty(dto.getPhone())
                &&StringUtils.isEmpty(dto.getPassword())
                &&StringUtils.isEmpty(dto.getEquipmentId()))) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
            //判断手机号密码是否为空,都不为空,使用手机号密码登录
        if (!StringUtils.isEmpty(dto.getPassword())&&!StringUtils.isEmpty(dto.getPhone())) {
            //根据手机号查询
            LambdaQueryWrapper<ApUser> query=new LambdaQueryWrapper<>();
            query.eq(ApUser::getPhone, dto.getPhone());
            ApUser aduser = this.getOne(query);
            //不存在提示错误消息
            if (aduser==null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            //存在获取盐 试用用户传入的密码加盐进行MD5计算
            String salt = aduser.getSalt();
            String pwd = dto.getPassword() + salt;
            String md5Str = DigestUtils.md5DigestAsHex(pwd.getBytes());
            //对比密码是否一样,
            if (!md5Str.equals(aduser.getPassword())) {
                //不一致返回密码错误
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);

            }
            //一直的话,使用jwt生成token 使用用户id生成
            Map<String, Object> claimMap = new HashMap<>();
            claimMap.put("userId", aduser.getId());
            claimMap.put("userName", aduser.getName());
            String token = AppJwtUtil.getToken(claimMap);
            //定义返回结果
            Map<String, Object> map = new HashMap<>();
            //脱敏处理
            aduser.setPhone(null);
            aduser.setPassword(null);
            aduser.setSalt(null);
            map.put("user", aduser);
            map.put("token", token);
            //通用响应
            return ResponseResult.okResult(map);
        }
        //设备id不为空,使用设备id进行登录,使用0生成token
        if (!StringUtils.isEmpty(dto.getEquipmentId())) {
            //一致的话,使用jwt生成token 使用用户id生成
            Map<String, Object> claimMap = new HashMap<>();
            claimMap.put("userId", 0);
            String token = AppJwtUtil.getToken(claimMap);
            //定义返回结果
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            //通用响应
            return ResponseResult.okResult(map);

        }
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
    }

    @Autowired
    private ArticleFeign articleFeign;
    @Autowired
    private IApUserFollowService followService;
//关注取消关注
    @Override
    public ResponseResult userFollow(UserRelationDto dto) {
        //获取当前用户的信息
        User user = AppThreadLocalUtil.get();
        if (user==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        int followId = 0;
        //构建关注对象
        ApUserFollow userFollow = new ApUserFollow();
        userFollow.setUserId(user.getUserId());
        userFollow.setUserName(user.getName());
        userFollow.setCreatedTime(new Date());
        //获取作者信息
        ResponseResult<ApAuthor> apAuthorResponseResult = articleFeign.getAuthorById(dto.getAuthorId());
        if (apAuthorResponseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            ApAuthor apAuthor = apAuthorResponseResult.getData();
            if (apAuthor!=null) {
                userFollow.setFollowId(apAuthor.getUserId());
                userFollow.setFollowName(apAuthor.getName());
                followId = apAuthor.getUserId();
                //判断操作是关注还是取消关注
                LambdaUpdateWrapper<ApUserFollow> query = new LambdaUpdateWrapper<>();
                query.eq(ApUserFollow::getFollowId, apAuthor.getUserId());
                if (dto.getOperation()==0) {
                    //关注
                    //保存用户信息
                    ApUserFollow one = followService.getOne(query);
                    if (one == null) {
                        //新增
                        followService.save(userFollow);
                    }
                }else {
                    //取消关注
                    //删除对应记录\
                    followService.remove(query);
                }
            }
        }
        //将操作行为发送到kafka
        FollowBehaviorDto followBehaviorDto = new FollowBehaviorDto();
        followBehaviorDto.setUserId(user.getUserId());
        followBehaviorDto.setFollowId(followId);
        followBehaviorDto.setEquipmentId(dto.getEquipmentId());
        followBehaviorDto.setOperation(dto.getOperation());
        String msg = JSON.toJSONString(followBehaviorDto);
        kafkaTemplate.send(followBehacirTopic, msg);
        return ResponseResult.okResult();
    }

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    @Value("${topic.followBehaviorTopic}")
    private String followBehacirTopic;

}
